/*
 * $Id: BinaryOperator.java,v 1.7 2003/06/29 10:52:30 znamenacek Exp $
 *
 * Copyright (c) Tomas Znamenacek
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package net.sf.vofce.guts;

import java.util.Stack;
import java.text.MessageFormat;

/**
 * Binary operator.
 *
 * @author Tomas Znamenacek
 */
public abstract class BinaryOperator extends AbstractOperator {

	/**
	 * Creates new binary operator.
	 */
	public BinaryOperator(
			int		priority,
			String		humanSyntax,
			String		TeXSyntax,
			String		XMLSyntax) {

		this.priority = priority;
		this.humanSyntax = humanSyntax;
		this.TeXSyntax = TeXSyntax;
		this.XMLSyntax = XMLSyntax;
	}

	/** Returns operator arity&mdash;2. */
	public int getArity() {

		return 2;
	}

	/** The operation represented by this operator. */
	public abstract double operation(double a, double b);
	
	public double evaluateSubTree() {
		
		return operation(leftChild.evaluateSubTree(), rightChild.evaluateSubTree());
	}
	
	public String toString(int parentPriority) {

		String value = MessageFormat.format(
			humanSyntax,
			new Object[] {
				leftChild.toString(priority),
				rightChild.toString(priority)
			}
		);
			
		return (parentPriority > priority) ?
			"(" + value +")"
			: value;
	}
	
	public String toTeX(int parentPriority) {

		String value = MessageFormat.format(
			TeXSyntax,
			new Object[] {
				leftChild.toTeX(priority),
				rightChild.toTeX(priority)
			}
		);
			
		return (parentPriority > priority) ?
			"\\left(" + value +"\\right)"
			: value;
	}
	
	public String toXML(int parentPriority) {

		String value = MessageFormat.format(
			XMLSyntax,
			new Object[] {
				leftChild.toXML(priority),
				rightChild.toXML(priority)
			}
		);
			
		return (parentPriority > priority) ?
			"<mo>(</mo>" + value +"<mo>)</mo>"
			: value;
	}
	
	public String toString() {

		return "<BinaryOperator::" + humanSyntax + ">";
	}

	public boolean equals(Object o) {

		return (o instanceof BinaryOperator) ?
			(((BinaryOperator) o).toString().equals(toString())) : false;
	}
}
